package com.example.jwt.security;

import com.alibaba.fastjson.JSON;
import com.example.jwt.entity.ResponseJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义认证拦截器
 *
 * @author : Charles
 * @date : 2021/12/2
 */
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    public AuthenticationEntryPointImpl() {}

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        log.warn("用户需要登录，访问[{}]失败，AuthenticationException={}", request.getRequestURI(), exception);
        // 登录失败，返回错误信息
        ResponseJson<Void> result = ResponseJson.error(exception.getMessage(), null);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(result));
    }

}
